// 电商管理后台API服务器
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3002;
const JWT_SECRET = 'your-secret-key';

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 确保上传目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// 模拟用户数据
const users = [
  {
    id: '1',
    username: 'admin',
    password: 'admin123',
    email: 'admin@example.com',
    role: 'admin',
    shopId: null,
    isActive: true,
    avatar: null,
  },
  {
    id: '2',
    username: 'seller1',
    password: 'seller123',
    email: 'seller1@example.com',
    role: 'seller',
    shopId: 'shop1',
    isActive: true,
    avatar: null,
  },
  {
    id: '3',
    username: 'service1',
    password: 'service123',
    email: 'service1@example.com',
    role: 'customer_service',
    shopId: 'shop1',
    isActive: true,
    avatar: null,
  },
];

// 权限配置
const rolePermissions = {
  admin: [
    'user:view', 'user:create', 'user:update', 'user:delete',
    'shop:view', 'shop:create', 'shop:update', 'shop:delete', 'shop:approve', 'shop:view_all',
    'product:view', 'product:create', 'product:update', 'product:delete', 'product:view_all',
    'order:view', 'order:update', 'order:view_all',
    'coupon:view', 'coupon:create', 'coupon:update', 'coupon:delete', 'coupon:create_platform', 'coupon:create_shop',
    'banner:view', 'banner:create', 'banner:update', 'banner:delete',
    'sales:view', 'sales:view_all',
    'chat:view', 'chat:reply', 'chat:manage',
    'system:config', 'system:log',
  ],
  seller: [
    'shop:view', 'shop:update', 'shop:view_own',
    'product:view', 'product:create', 'product:update', 'product:delete', 'product:view_own',
    'order:view', 'order:update', 'order:view_own',
    'coupon:view', 'coupon:create', 'coupon:update', 'coupon:delete', 'coupon:create_shop',
    'sales:view', 'sales:view_own',
    'chat:view', 'chat:reply',
  ],
  customer_service: [
    'chat:view', 'chat:reply',
    'order:view', 'order:view_own',
    'product:view', 'product:view_own',
  ],
};

// JWT验证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ success: false, message: '未提供访问令牌' });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ success: false, message: '访问令牌无效' });
    }
    req.user = user;
    next();
  });
};

// 登录接口
app.post('/api/admin/auth/login', (req, res) => {
  const { username, password } = req.body;

  // 查找用户
  const user = users.find(u => u.username === username && u.password === password);

  if (!user) {
    return res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    });
  }

  if (!user.isActive) {
    return res.status(401).json({
      success: false,
      message: '账户已被禁用'
    });
  }

  // 生成JWT token
  const token = jwt.sign(
    {
      id: user.id,
      username: user.username,
      role: user.role,
      shopId: user.shopId
    },
    JWT_SECRET,
    { expiresIn: '24h' }
  );

  // 返回用户信息和权限
  const userInfo = {
    id: user.id,
    username: user.username,
    email: user.email,
    role: user.role,
    shopId: user.shopId,
    isActive: user.isActive,
    avatar: user.avatar,
  };

  res.json({
    success: true,
    data: {
      user: userInfo,
      token,
      permissions: rolePermissions[user.role] || [],
    }
  });
});

// 获取当前用户信息
app.get('/api/admin/auth/me', authenticateToken, (req, res) => {
  const user = users.find(u => u.id === req.user.id);

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在'
    });
  }

  const userInfo = {
    id: user.id,
    username: user.username,
    email: user.email,
    role: user.role,
    shopId: user.shopId,
    isActive: user.isActive,
    avatar: user.avatar,
  };

  res.json({
    success: true,
    data: userInfo
  });
});

// 登出接口
app.post('/api/admin/auth/logout', authenticateToken, (req, res) => {
  // 在实际应用中，这里应该将token加入黑名单
  res.json({
    success: true,
    message: '登出成功'
  });
});

// 刷新token
app.post('/api/admin/auth/refresh', authenticateToken, (req, res) => {
  const newToken = jwt.sign(
    {
      id: req.user.id,
      username: req.user.username,
      role: req.user.role,
      shopId: req.user.shopId
    },
    JWT_SECRET,
    { expiresIn: '24h' }
  );

  res.json({
    success: true,
    data: {
      token: newToken
    }
  });
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'API服务正常运行',
    timestamp: new Date().toISOString()
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    message: '服务器内部错误'
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`模拟服务器运行在 http://localhost:${PORT}`);
  console.log('测试账户:');
  console.log('- 管理员: admin / admin123');
  console.log('- 商家: seller1 / seller123');
  console.log('- 客服: service1 / service123');
});

module.exports = app;
